package cn.itcast.health.mobile.controller;


import cn.itcast.health.commons.utils.LogUtils;
import cn.itcast.health.mobile.logs.OperationLog;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 朱贺
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private DefaultKaptcha defaultKaptcha;


    @RequestMapping("/code/{deviceId}")
    @OperationLog(moduleName = LogUtils.Module.MOBILE, operationType = LogUtils.Type.QUERY, operationContent = "提供给移动端手机号短信防盗刷的图形验证码")
    public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
        Assert.notNull(deviceId, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        System.out.println("图形验证码 : " + text);
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        //生成的验证码写入redis
        jedisPool.getResource().setex(deviceId,60*5,text);
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        //将图片写回浏览器
        ImageIO.write(image, "JPEG", out);
    }
}
